<template>
  <a-card title="菜单管理" class="general-card" :bordered="false">
    <a-tabs v-model="currentMenu" @tab-click="changeMenu">
      <a-tab-pane v-for="(item, index) in menuList" :key="item.value" :title="item.label" />
    </a-tabs>
    <a-row class="action">
      <a-switch v-model="strict">
        <template #checked> 级联</template>
        <template #unchecked>单选</template>
      </a-switch>
      <a-button @click="addRootMenu">添加顶级菜单</a-button>
      <a-button @click="addMenu">添加子菜单</a-button>
      <a-button @click="delAll">批量删除</a-button>
      <a-dropdown @select="handleDropdown">
        <a-button>更多操作</a-button>
        <template #content>
          <a-doption value="refresh">刷新</a-doption>
          <a-doption value="expandOne">收合所有</a-doption>
          <a-doption value="expandTwo">展开一级</a-doption>
          <a-doption value="expandThree">展开二级</a-doption>
          <a-doption value="expandAll">展开所有</a-doption>
        </template>
      </a-dropdown>
    </a-row>
    <a-row style="margin: 16px 0">
      <a-col :span="8">
        <a-alert type="warning">当前选择编辑： <span>{{ editTitle }}</span><a-button v-if="form.id" @click="cancelSelect"
            type="text">取消选择</a-button>
        </a-alert>
        <div>
          <a-input-search style="margin-bottom: 8px; margin-top: 8px" v-model="searchKey" change="" />
        </div>
        <div class="tree-bar" :style="{ maxHeight: maxHeight }" :key="isShowTree">
          <a-tree :check-strictly="!strict" :data="originTreeData"  @select="handleCateChange" @check="handleCheckChange"
            v-model:checked-keys="checkedKeys" v-model:expanded-keys="expandedKeys" :checkable="true"
            checked-strategy="all" :fieldNames="{ key: 'id', icon: 'customIcon' }">
            <template #title="nodeData">
              <template v-if="(index = getMatchIndex(nodeData?.title))">{{
                nodeData?.title
                }}</template>
              <span v-else>
                {{ nodeData?.title?.substr(0, index) }}
                <span style="color: var(--color-primary-light-4)">{{
                  nodeData?.title?.substr(index, searchKey.length)
                  }}</span>
                {{ nodeData?.title?.substr(index + searchKey.length) }}
              </span>
            </template>
          </a-tree>
        </div>
      </a-col>
      <a-col :span="16">
        <a-form ref="formRef" :model="form" :style="{ width: '600px' }">
          <a-form-item field="type" label="类型">
            <div v-if="form.level == 0"><icon-send /><span>顶级菜单</span></div>
            <div v-if="form.level != 0"><icon-drive-file /><span>页面菜单</span></div>
          </a-form-item>
          <a-form-item field="title" label="菜单名称">
            <a-input v-model="form.title" placeholder="请输入菜单名称" />
          </a-form-item>
          <a-form-item field="icon" tooltip="输入内容为 arco icon 的值" label="菜单图标">
            <a-input v-model="form.icon" placeholder="请输入菜单图标" />
          </a-form-item>
          <a-form-item field="path" label="路由地址" :rules="[REQUIRED]" v-if="form.level != 0">
            <a-tooltip content="路由地址，英文唯一，跳转页面，路径展示用" position="bl">
              <a-input v-model="form.path" />
            </a-tooltip>
          </a-form-item>
          <a-form-item field="name" label="路由名称" :rules="[REQUIRED]">
            <a-tooltip content="路由name，需英文唯一，跳转页面用" position="bl">
              <a-input v-model="form.name" />
            </a-tooltip>
          </a-form-item>
          <a-form-item field="frontRoute" label="文件路径" :rules="[REQUIRED]" v-if="form.level != 0">
            <a-input v-model="form.frontRoute" />
          </a-form-item>
          <a-form-item field="permission" label="权限url" v-if="form.level != 0">
            <a-textarea placeholder="请输入权限url，*号模糊匹配，逗号分割" allow-clear v-model="form.permission" />
            <!--<div class="desc"></div>-->
          </a-form-item>
          <a-form-item field="sortOrder" label="排序值" :rules="[REQUIRED]">
            <a-tooltip content="值越小越靠前，支持小数" position="rt">
              <a-input-number v-model="form.sortOrder" :style="{ width: '320px' }" class="input-demo" :min="0"
                :max="1000" />
            </a-tooltip>
          </a-form-item>
          <a-form-item>
            <a-button html-type="submit" style="margin-right: 5px" type="primary" @click="submitEdit">修改并保存</a-button>
            <a-button html-type="submit" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
    <a-modal v-model:visible="modalVisible" @cancel="handleClose" :align-center="false" :footer="false">
      <template #title>{{ modalTitle }}</template>
      <a-form ref="formAddRef" :model="formAdd" layout="horizontal" auto-label-width @submit="handleConfirm">
        <div v-if="showParent"><a-form-item label="上级节点：">{{ form.title }}</a-form-item></div>
        <a-form-item field="type" label="类型">
          <div v-if="!showParent"><icon-send /><span>顶级菜单</span></div>
          <div v-if="showParent"><icon-drive-file /><span>页面菜单</span></div>
        </a-form-item>
        <a-form-item field="title" label="菜单名称" :rules="[REQUIRED]">
          <a-input v-model="formAdd.title" />
        </a-form-item>
        <a-form-item field="icon" tooltip="输入内容为 arco icon 的值" label="菜单图标">
            <a-input v-model="formAdd.icon" placeholder="请输入菜单图标" />
          </a-form-item>
        <a-form-item field="path" label="路由地址" v-if="showParent" :rules="[REQUIRED]">
          <a-input v-model="formAdd.path" />
        </a-form-item>
        <a-form-item field="name" label="路由名称" :rules="[REQUIRED]">
          <a-tooltip content="路由name，需英文唯一，跳转页面用" position="bl">
            <a-input v-model="formAdd.name" />
          </a-tooltip>
        </a-form-item>
        <a-form-item field="frontRoute" label="文件路径" v-if="showParent">
          <a-input v-model="formAdd.frontRoute" />
        </a-form-item>
        <a-form-item field="permission" label="权限url" v-if="showParent">
          <a-textarea placeholder="请输入权限url，*号模糊匹配，逗号分割" allow-clear v-model="formAdd.permission" />
          <!--<div class="desc"></div>-->
        </a-form-item>
        <a-form-item field="sortOrder" label="排序值" :rules="[REQUIRED]">
          <a-tooltip content="值越小越靠前，支持小数" position="rt">
            <a-input-number v-model="formAdd.sortOrder" :style="{ width: '320px' }" class="input-demo" :min="0"
              :max="1000" />
          </a-tooltip>
        </a-form-item>
        <a-form-item label="操作"><a-button type="primary" html-type="submit">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import {
  addPermission,
  addStorePermission,
  deletePermission,
  deleteStorePermission,
  editPermission,
  editStorePermission,
  getAllPermissionList,
  getStoreAllPermissionList,
} from '@/api/setting';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { REQUIRED } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { onMounted, ref, watch } from 'vue';

const index = ref<any>();
const currentMenu = ref<string | number>('');
const menuList = ref<any>([
  {
    label: '管理端',
    value: 'MANAGE',
  },
  {
    label: '商家端',
    value: 'STORE',
  },
]);
const modal = useCurrentInstance().globalProperties?.$modal; // 获取modal
const maxHeight = ref(); // 最大高度
const users = ref({}); // 角色列表
const strict = ref(true); // 级联还是单选
const modalTitle = ref(''); // 模态框标题
const showParent = ref(false); // 是否展示父级
const modalVisible = ref(false); // modal显隐
const formAdd = ref({}) as any; // 新增部门表单
const selectList = ref([]); // 已选列表
const checkedKeys = ref([]);
const expandedKeys = ref([]);
const editTitle = ref(''); // 编辑标题
const selectedRole = ref([]); // 选择得角色
const form = ref<any>({
  id: '',
  title: '',
  icon: '',
  path: '',
  frontRoute: '',
  parentId: '',
  sortOrder: 0,
  level: 0,
  permission: '',
});

const originTreeData = ref();
const originTreeDataCopy = ref();
const isShowTree = ref(1);
const temp = ref();
const searchData = (keyword: string) => {
  isShowTree.value += 1;
  const loop = (data: any) => {
    const result: any = [];
    data.value.forEach((item: any) => {
      if (item.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        temp.value = item.children;
        const filterData = loop(temp);
        if (filterData.length) {
          result.push({ ...item, children: filterData });
        }
      }
    });
    return result;
  };
  return loop(originTreeDataCopy);
};

const searchKey = ref('');
// const treeData = computed(() => {
//   if (!searchKey.value) return originTreeData;
//   // return searchData(searchKey.value);
// });
const formRef = ref();
const formAddRef = ref();
const expandLevel = ref<number>(1); // 展开层级

function getMatchIndex(title: string) {
  if (!searchKey.value) return -1;
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
}

// 切换菜单
const changeMenu = (v: string | number) => {
  currentMenu.value = v;
  getAllList();
};

// 获取所有菜单
const getAllList = async () => {
  let res: any;
  if (currentMenu.value === 'STORE') {
    res = await getStoreAllPermissionList();
  } else {
    res = await getAllPermissionList();
  }
  if (res.data.success) {
    originTreeData.value = res.data.result.map((item: any) => {
      // delete item.icon;
      return item;
    });
    // 仅展开指定级数
    let allExpandedKeys: any = [];
    // 收合所有
    if (expandLevel.value === 1) {
      expandedKeys.value = allExpandedKeys;
    }
    // 展开一级
    if (expandLevel.value === 2) {
      allExpandedKeys = originTreeData.value.map((item: any) => item.id);
      expandedKeys.value = allExpandedKeys;
    }
    // 展开二级
    if (expandLevel.value === 3) {
      originTreeData.value.map((item: any) => {
        allExpandedKeys.push(item.id);
        return item.children.map((itemChild: any) => {
          allExpandedKeys.push(itemChild.id);
          return itemChild;
        });
      });
      expandedKeys.value = allExpandedKeys;
    }
    originTreeDataCopy.value = originTreeData.value;
  }
};
// 添加顶级菜单
const addRootMenu = () => {
  modalTitle.value = '添加顶级菜单';
  showParent.value = false;
  formAdd.value = {
    level: 0,
    sortOrder: 0,
  };
  modalVisible.value = true;
};
// 添加子菜单
const addMenu = () => {
  if (form.value.id == '' || form.value.id == null) {
    Message.warning('请先点击选择一个菜单权限节点');
    return;
  }
  modalTitle.value = '添加子节点';
  showParent.value = true;
  if (form.value.level == 2) {
    modal.confirm({
      title: '抱歉，不能添加啦',
      content: `仅支持2级菜单目录`,
      alignCenter: false,
    });
    return;
  }
  formAdd.value = {
    parentId: form.value.id,
    level: Number(form.value.level) + 1,
    sortOrder: 0,
    permission: '', // 权限url
  };
  if (form.value.level == 0) {
    formAdd.value.path = '/';
    formAdd.value.frontRoute = 'Main';
  }
  modalVisible.value = true;
};
const init = () => {
  getAllList();
};
// 选择分类回调（点击树节点时触发）
const handleCateChange = (selectedKeys: any, data: any) => {
  editTitle.value = data.node.title;
  form.value = data.node;
  // getUserByDepartmentId(data.node.id).then((res) => {
  //   const way = [] as any;
  //   res.data.result &&
  //     res.data.result.forEach((item) => {
  //       way.push(item.roleId);
  //     });
  //   selectedRole.value = way;
  // });
  // getRoleList({ pageNumber: 1, pageSize: 10000 }).then((res) => {
  //   if (res.data.success) {
  //     users.value = res.data.result.records;
  //     form.value = data.node;
  //     // console.log(users.value,'角色列表')
  //   }
  // });
};
// 部门选择事件
const handleCheckChange = (newCheckedKeys: any, event: any) => {
  selectList.value = event.checkedNodes;
};
// 添加
const handleConfirm = async () => {
  const auth = await formAddRef.value?.validate();
  if (!auth) {
    if (currentMenu.value === 'STORE') {
      addStorePermission(formAdd.value).then((res: any) => {
        if (res.data.success) {
          Message.success('添加成功');
          init();
        }
      });
    } else {
      addPermission(formAdd.value).then((res: any) => {
        if (res.data.success) {
          Message.success('添加成功');
          modalVisible.value = false;
          init();
        }
      });
    }
  }
};
// 取消添加部门
const handleClose = () => {
  modalVisible.value = false;
};
// 批量删除
const delAll = () => {
  if (checkedKeys.value.length <= 0) {
    Message.warning('您还未勾选要删除的数据');
    return;
  }
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除所选的${checkedKeys.value.length}条数据?`,
    alignCenter: false,
    onOk: async () => {
      let ids = '';
      selectList.value.forEach((item: any) => {
        ids += `${item.id},`;
      });
      const joinId = ids.substring(0, ids.length - 1);
      let res;
      if (currentMenu.value === 'STORE') {
        res = await deleteStorePermission(joinId);
      } else {
        res = await deletePermission(joinId);
      }
      if (res.data.success) {
        selectList.value = [];
        Message.success('删除成功');
        init();
      }
    },
  });
};
// 取消选择
const cancelSelect = () => {
  formRef.value.resetFields();
  form.value.id = '';
  editTitle.value = '';
  getAllList();
};
// 提交表单
const submitEdit = async () => {
  if (!form.value.id) {
    Message.warning('请先点击选择要修改的菜单节点');
    return;
  }
  if (form.value.sortOrder == null) {
    form.value.sortOrder = 0;
  }
  // 删除一些之前添加的无用字段
  // delete form.value.icon;
  delete form.value.frontComponent;
  delete form.value.buttonType;
  delete form.value.updateTime;
  delete form.value.selected;
  delete form.value.description;
  delete form.value.children;
  const auth = await formRef.value?.validate();
  if (!auth) {
    if (currentMenu.value === 'STORE') {
      editStorePermission(form.value).then((res: any) => {
        if (res.data.success) {
          Message.success('编辑成功');
          init();
        }
      });
    } else {
      editPermission(form.value).then((res: any) => {
        if (res.data.success) {
          Message.success('编辑成功');
          init();
        }
      });
    }
  }
  // const roleWay = [];
  // selectedRole.value.forEach((item) => {
  //   const role = {
  //     departmentId: form.value.id,
  //     roleId: item,
  //   };
  //   roleWay.push(role);
  // });
  // Promise.all([
  //   editDepartment(form.value.id, form.value),
  //   updateDepartmentRole(form.value.id, roleWay),
  // ]).then((res) => {
  //   if (res[0].data.success) {
  //     Message.success('编辑成功');
  //     init();
  //   }
  // });
};
// 重置表单
const handleReset = () => {
  formRef.value.resetFields(); // 清空表单
  // form.value.frontRoute = '';
  getAllList();
};

// 批量操作
const handleDropdown = (v: any) => {
  //  刷新
  if (v === 'refresh') {
    expandLevel.value = 1;
    getAllList();
  }
  // 收合所有
  if (v === 'expandOne') {
    expandLevel.value = 1;
    getAllList();
  }
  // 展开一级
  if (v === 'expandTwo') {
    expandLevel.value = 2;
    getAllList();
  }
  // 展开两级
  if (v === 'expandThree') {
    expandLevel.value = 3;
    getAllList();
  }
  // 展开所有
  if (v === 'expandAll') {
    expandLevel.value = 3;
    getAllList();
  }
};

// 初始化
onMounted(() => {
  // 计算高度
  const height = document.documentElement.clientHeight;
  maxHeight.value = `${Number(height - 287)}px`;
  getAllList();
});

watch(
  () => searchKey.value,
  (newValue, oldValue) => {
    if (newValue) {
      originTreeData.value = searchData(searchKey.value);
    } else {
      getAllList();
    }
  }
);
</script>

<style scoped lang="less">
.action {
  .arco-btn {
    margin-left: 10px;
  }
}

.tree-bar {
  overflow: auto;
  margin-top: 5px;
  position: relative;
  min-height: 80px;
}

.tree-bar::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.tree-bar::-webkit-scrollbar-thumb {
  border-radius: 4px;
  -webkit-box-shadow: inset 0 0 2px #d1d1d1;
  background: #e4e4e4;
}
</style>
